package com.bonc.modules.fileManage.contorller;

import cn.fzb.util.web.download.DownloadWeb;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonc.common.utils.Result;
import com.bonc.common.utils.UUIDUtils;
import com.bonc.modules.fileManage.service.FileService;
import com.bonc.modules.sys.controller.AbstractController;
import com.bonc.modules.sys.entity.SysUserEntity;
import com.bonc.modules.sys.service.SysUserService;
import com.bonc.modules.target.Util.DateUtils;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController extends AbstractController {

    @Autowired
    private FileService fileService;

    @Autowired
    private SysUserService sysUserService;

    @Value("${custMonitorFile}")
    private String filePath;

    @PostMapping("/fileUpload")
    public Result FileUpload(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params , HttpServletRequest request) {

        //基于inputFile创建一个文件输入流
        InputStream is = null;
        OutputStream os = null;
        try {
            MultipartRequest multipartRequest = (MultipartRequest) request;
            /*准备文件数据*/
            //文件ID--自动生成
            String fileId = "";
            //父文件ID--根据文件类型和所属区域来判断
            String parFileId = "";
            //文件名称
            MultipartFile excelFile = multipartRequest.getFile("file");
            String fileName = URLDecoder.decode(excelFile.getOriginalFilename(),"UTF-8") ;
            //文件描述--准备字段，目前先空着。
            String fileDesc = "";
            //文件类型--页面URL方式传值。
            String fileType = "";
            //上传日期--服务端系统生成。
            String uploadDate = "";
            //上传人--来自session域。
            String uploadPerson = "";
            //文件URL--
            String fileUrl = "";
            //备份--准备字段，目前先空着。
            String bak = "0";

            fileId = UUIDUtils.getRandomNumNoZero(9);
            String fileTypeNum = params.get("fileType") + "";
            Map<String,String> typeMap =  this.fileService.getFileManageType(fileTypeNum);
            fileType =typeMap.get("fileType");
//            if (fileTypeNum.equals("1")) {
//                fileType = "制度规范";
//            }
//            if (fileTypeNum.equals("2")) {
//                fileType = "满意度报告";
//            }
//            if (fileTypeNum.equals("3")) {
//                fileType = "专题研究";
//            }
//            if (fileTypeNum.equals("4")) {
//                fileType = "案例分析";
//            }
//            if (fileTypeNum.equals("5")) {
//                fileType = "服务管理最佳实践";
//            }

            String regionNum = params.get("regionCode") + "";
            parFileId = fileTypeNum + regionNum;

            uploadDate = DateUtils.getNow("yyyy-MM-dd");
            System.out.println("文件上传用户Id"+getUserId());
            SysUserEntity user = sysUserService.getById(getUserId());
            System.out.println("文件上传用户"+user);
            uploadPerson = user.getUserCnName()+ "";

            fileUrl = "\\" + fileName;
            is = excelFile.getInputStream();
            //设置上传文件目录
            String uploadPath = filePath;
            //设置目标文件
            File toFile = new File(uploadPath, fileName);
            //创建一个输出流
            os = new FileOutputStream(toFile);
            //设置缓存
            byte[] buffer = new byte[1024];
            int length = 0;
            //读取myFile文件输出到toFile文件中
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            System.out.println("上传文件名" + fileName);
//            System.out.println("上传文件类型"+inputFileContentType);


            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("fileId", fileId);
            paramMap.put("parFileId", parFileId);
            paramMap.put("fileName", fileName);
            paramMap.put("fileDesc", fileDesc);
            paramMap.put("fileType", fileType);
            paramMap.put("uploadDate", uploadDate);
            paramMap.put("uploadPerson", uploadPerson);
            paramMap.put("fileUrl", fileUrl);
            paramMap.put("bak", bak);

            // 如果记录存在，就删除原来记录，再重新插入记录。
            if (this.fileService.queryFileByFileName(paramMap) == true) {
                this.fileService.delFile(paramMap);
            }
            this.fileService.importFileData(paramMap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            try {
                is.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.ok("文件上传成功！");
    }


    /**
     * @Description: 文档下载
     * @param @return
     * @return String
     * @throws
     * @author  liudong
     * @date 2022年2月22日
     */
    @GetMapping("/fileDownload")
    public void fileDownload (@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        String fileName = URLDecoder.decode(params.get("fileName")+"") ;
 //       String filePath = request.getSession().getServletContext().getRealPath("/")+"custMonitorFile/" + fileName;
        String downFilePath =filePath +"/"+ fileName;
        File file = new File(downFilePath);
        if(!file.exists()){
            downFilePath = request.getSession().getServletContext().getRealPath("/")+"custMonitorDefaultFile/default.txt";
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        DownloadWeb.getDownloadWeb(downFilePath, request, response).download();
    }

    /**
     *  文件删除 逻辑删除 不删除实体文件
     * @param params
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/deleteFileData")
    public Result deleteFileData(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response){
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("fileId",params.get("fileId")==null?"":params.get("fileId")+"");
        paramMap.put("fileName",params.get("fileName")==null?"":params.get("fileName")+"");
        Integer del = this.fileService.deleteFileData(paramMap);
        return Result.ok("文件删除成功");
    }

    /**
     *  文件列表
     * @param params
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/queryFileManageInfo")
    public Result queryFileManageInfo(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response){
        Page page  = this.fileService.queryFileManagePage(params);
        return Result.ok().put("page", page);
    }

    /**
     *  文件归类
     * @param
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/queryFileType")
    public Result queryFileType(HttpServletRequest request, HttpServletResponse response){
        List<Map<String,Object>> list = this.fileService.queryFileType();
        return Result.ok().put("data", list);
    }

}
